<template>
  <view v-if="detailData.articleId" class="content">
    <view class="lh-flex lh-items-center lh-content-center lh-p-30 lh-pb-0">
      <view class="lh-flex-1 lh-flex lh-items-center"
            @click="goUserPage(detailData.authorId)">
        <up-image
          :src="`${env.VITE_OSS_BUCKET}${detailData.images}`"
          width="86rpx"
          height="86rpx"
          mode="aspectFill"
          shape="circle"
        >
          <template v-slot:loading>
            <up-loading-icon></up-loading-icon>
          </template>
        </up-image>
        <view
          class="lh-flex-1 lh-flex lh-items-start lh-content-around lh-flex-col lh-ml-16 lh-h-86"
        >
          <view class="baseDataText1 u-line-1">{{ detailData.authorName }}</view>
          <view class="baseDataText2">
            {{ filterTime(detailData.createdTimestamp) }}
            <template v-if="detailData.location">| {{ detailData.location }}</template>
          </view>
        </view>
      </view>
      <view class="ml32" @click="switchFollow">
        <FollowStyle :isFollow="isFollow" size="large"/>
      </view>
    </view>
    <view class="detailData">
      <view class="title">
        <view class="articleType">
          <ArticleTypeStyle :type="detailData.articleType"/>
        </view>
        <view class="text u-line-2">
          {{ detailData.title }}
        </view>
      </view>
      <view class="mb20">
        <up-swiper
          :list="images"
          @change="(e) => (imgSwiperCurrent = e.current)"
          :autoplay="false"
          height="602rpx"
        >
          <template v-slot:indicator>
            <view class="indicator">
              <view
                class="indicator__dot"
                v-for="(item, index) in images"
                :key="index"
                :class="[
                  index === imgSwiperCurrent && 'indicator__dot--active',
                ]"
              ></view>
            </view>
          </template>
        </up-swiper>
      </view>
    </view>
    <view v-show="false">{{ distance }}</view>
    <view
      class="lh-pl-74 lh-pr-74 lh-flex lh-items-center lh-justify-between lh-text-20 lh-font-[#666]"
    >
      <view class="lh-flex lh-items-center">
        <u-icon name="empty-address" color="#666"></u-icon>
        {{ distanceRef }}
      </view>
      <view class="lh-flex lh-items-center">
        <u-icon name="eye" color="#666"></u-icon>
        <view class="lh-ml-12"> {{ detailData.viewCount || 0 }}浏览</view>
      </view>
    </view>
  </view>
</template>

<script setup>
import {ref, toRef, computed, getCurrentInstance} from 'vue';
import {useStore} from 'vuex';
import FollowStyle from '@/components/FollowStyle/index.vue';
import ArticleTypeStyle from '@/components/ArticleTypeStyle/index.vue';

import useUserInfo from '@/hooks/useUserInfo.js';
import initQQmap from '@/utils/initQQmap.js';

import {filterTime} from '@/utils/formatTime.js';
import followManagement from '@/api/followManagement'
import articleManagement from '@/api/articleManagement.js'

const store = useStore();
store.dispatch('position/getPosition', {
  settingTitle: '请求授权当前位置',
  settingContent: '需要获取您的地理位置，看看您与发帖人的距离！',
});
const latitude = toRef(store.state.position, 'latitude');
const longitude = toRef(store.state.position, 'longitude');

const props = defineProps({
  detailId: {
    type: Number,
    required: true,
  },
});
const detailId = toRef(props, 'detailId');
const isFollow = ref(false);

const {userInfo} = useUserInfo();

const detailData = ref({});
const imgSwiperCurrent = ref(0);
const images = computed(() => {
  return detailData.value.images.split(',').map((item) => {
    item = import.meta.env.VITE_OSS_BUCKET + item;
    return item;
  });
});
const getDetail = async () => {
  const res = await articleManagement.getArticleDetail(detailId.value);
  console.log("getDetail",res);
  detailData.value = res.data;

  followManagement.checkFollowedUser(detailData.value.authorId,userInfo.value.userId).then((res) => {
    console.log("checkFollowedUser",res);
    if (res.data) {
      isFollow.value = res.data;
    }
  }).catch((err) => {
    console.log(err);
  });
};

getDetail();

const distanceRef = ref(0);
const distance = computed(async () => {
  if (
    latitude.value !== 0 &&
    longitude.value !== 0 &&
    detailData.value.longitude !== 0 &&
    detailData.value.latitude !== 0
  ) {
    const res = await new Promise((resolve) => {
      initQQmap().calculateDistance({
        mode: 'straight',
        from: {
          latitude: latitude.value,
          longitude: longitude.value,
        },
        to: [
          {
            latitude: detailData.value.latitude,
            longitude: detailData.value.longitude,
          },
        ],
        success: ({status, result}) => {
          console.log('result', result);
          if (status !== 0) {
            distanceRef.value = 0;
            resolve(0);
          } else {
            distanceRef.value = result.elements[0].distance;
            resolve(result.elements[0].distance);
          }
        },
        fail: () => {
          distanceRef.value = 0;
          resolve(0);
        },
      });
    });
    console.log('distance res', res);
    return res;
  }
  return 0;
});


function switchFollow() {
  isFollow.value = !isFollow.value;
  if (isFollow.value) {
    followManagement.newFollowPair({
      followedUserId: detailData.value.authorId,
      followedUserName: detailData.value.authorName,
      followedUserProfileUrl: detailData.value.authorProfileUrl,

      followingUserId: userInfo.value.userId,
      followingUserName: userInfo.value.userName,
      followingUserProfileUrl: userInfo.value.profileUrl,
    }).then((res) => {
      console.log(res);
    }).catch((err) => {
      console.log(err);
    });
  } else {

  }
}

function goUserPage(userId) {
  uni.switchTab({
    url: `/pages/my/index`,
  });
  // uni.$emit('goUserPage', userId);
  uni.$emit('update',{msg:'页面更新'})

}
</script>

<style lang="scss">
.baseDataText1 {
  color: #666666;
  font-weight: 500;
  font-size: 28rpx;
}

.baseDataText2 {
  color: #999999;
  font-size: 22rpx;
}

.detailData {
  margin-top: 20rpx;
  margin-bottom: 20rpx;
  padding: 0 74rpx;
}

.title {
  position: relative;
  margin-bottom: 20rpx;

  .text {
    font-size: 30rpx;
    font-weight: 500;
    color: #333333;
    text-indent: 3.2em;
    line-height: 40rpx;
  }
}

.articleType {
  position: absolute;
  top: 2rpx;
  left: 0;
}

.indicator {
  display: flex;
  justify-content: center;

  &__dot {
    height: 6px;
    width: 6px;
    border-radius: 100px;
    background-color: rgba(255, 255, 255, 0.35);
    margin: 0 5px;
    transition: background-color 0.3s;

    &--active {
      background-color: #ffffff;
    }
  }
}

.viewCount {
}
</style>
